/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.leetCode._1_Array_Linked_List;

import com.leetCode.structure.ListNode;

import java.util.HashSet;
import java.util.Set;
import static com.leetCode.structure.ListNode.*;

/**
 * @author : sunzb(sunzb@hsit.com.cn)
 * @date: 2019/5/10
 */
//Medium
public class _04_142_LinkedListCycle2 {

    public static ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        Set<ListNode> visited = new HashSet<>();
        ListNode cur = head;
        while (cur != null) {
            if (visited.contains(cur)) {
                return cur;
            }
            visited.add(cur);
            cur = cur.next;
        }
        return null;
    }

    public static ListNode detectCycle1(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return null;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        if (fast.next == slow) {
            return slow;
        }
        ListNode cur = head;
        while (cur != slow) {
            fast = fast.next;
            while (fast != slow) {
                if (fast == cur) {
                    return cur;
                }
                fast = fast.next;
            }
            cur = cur.next;
        }
        return null;
    }

    // ?_?
    public static ListNode detectCycle2(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                slow = head;
                while (fast != slow) {
                    System.out.println(String.format("(%s,%s)", fast.val, slow.val));
                    fast = fast.next;
                    slow = slow.next;
                }
                return slow;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
        ListNode l6 = new ListNode(6);
        head.next = l1;
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        l6.next = l3;
        System.out.println(str(detectCycle2(head)));
    }
}
